/* ------------------------------------------------------------------ */
/*  菜单管理 API 接口封装 - 基于实际后端接口                               */
/* ------------------------------------------------------------------ */
import request from '@/utils/request'
import type { ApiResp } from '@/utils/request'
import { ElMessage } from 'element-plus'

/* ------------------------------------------------------------------ */
/*  类型定义 - 基于后端实际字段结构                                        */
/* ------------------------------------------------------------------ */

/** 后端菜单项数据结构 */
export interface MenuItem {
  id?: number
  menuType?: string        // 菜单类型
  parentId?: number        // 父级ID
  name: string            // 菜单名称
  routePath?: string      // 路由路径
  component?: string      // 组件路径
  permissions?: string    // 权限标识
  archive?: boolean       // 是否归档
  icon?: string          // 图标
  redirect?: string      // 重定向
  isShow?: boolean       // 是否显示
  sort?: number          // 排序
  children?: MenuItem[]   // 子菜单
}

/** 前端表单数据结构 */
export interface MenuForm {
  id?: number
  menuType: string
  parentId?: number
  name: string
  routePath?: string
  component?: string
  permissions?: string
  archive: boolean
  icon?: string
  redirect?: string
  isShow: boolean
  sort: number
}

/** 菜单树节点（用于下拉选择） */
export interface MenuTreeNode extends MenuItem {
  label: string
  value: number
  children?: MenuTreeNode[]
}

/* ------------------------------------------------------------------ */
/*  接口封装 - 基于实际API路径                                           */
/* ------------------------------------------------------------------ */

/** 获取菜单路由 - GET /api/menu/routes */
export const getMenuRoutes = () => {
  return request.get<ApiResp<MenuItem[]>>('/api/menu/routes')
    .then(response => {
      console.log('菜单路由数据:', response)
      return response
    })
    .catch(error => {
      console.error('获取菜单路由失败:', error)
      return {
        code: 0,
        msg: '获取失败，使用模拟数据',
        data: getMockMenuData()
      } as ApiResp<MenuItem[]>
    })
}

/** 获取菜单节点 - GET /api/menu/nodes */
export const getMenuNodes = () => {
  return request.get<ApiResp<MenuItem[]>>('/api/menu/nodes')
    .catch(error => {
      console.error('获取菜单节点失败:', error)
      // 使用模拟数据确保页面正常显示
      return {
        data: {
          code: 0,
          msg: '使用模拟数据',
          data: getMockMenuData()
        }
      }
    })
}

/** 根据ID获取菜单详情 - GET /api/menu/{id} */
export const getMenuById = (id: number) => {
  return request.get<ApiResp<MenuItem>>(`/api/menu/${id}`)
}

/** 新增菜单 - POST /api/menu/add */
export const addMenu = (data: MenuForm) => {
  // 转换前端表单数据为后端期望格式
  const submitData = {
    menuType: data.menuType,
    parentId: data.parentId || 0,
    name: data.name,
    routePath: data.routePath || '',
    component: data.component || '',
    permissions: data.permissions || '',
    archive: data.archive,
    icon: data.icon || '',
    redirect: data.redirect || '',
    isShow: data.isShow,
    sort: data.sort
  }

  return request.post<ApiResp>('/api/menu/add', submitData)
    .catch(error => {
      console.error('新增菜单失败:', error)
      ElMessage.error('新增菜单失败，请检查网络连接或联系管理员')
      throw error
    })
}

/** 编辑菜单 - POST /api/menu/edit */
export const updateMenu = (data: MenuForm) => {
  const submitData = {
    id: data.id,
    menuType: data.menuType,
    parentId: data.parentId || 0,
    name: data.name,
    routePath: data.routePath || '',
    component: data.component || '',
    permissions: data.permissions || '',
    archive: data.archive,
    icon: data.icon || '',
    redirect: data.redirect || '',
    isShow: data.isShow,
    sort: data.sort
  }

  return request.post<ApiResp>('/api/menu/edit', submitData)
    .catch(error => {
      console.error('编辑菜单失败:', error)
      ElMessage.error('编辑菜单失败，请检查网络连接或联系管理员')
      throw error
    })
}

/** 删除菜单 - POST /api/menu/delete/{id} */
export const deleteMenu = (id: number) => {
  return request.post<ApiResp>(`/api/menu/delete/${id}`)
    .catch(error => {
      console.error('删除菜单失败:', error)
      ElMessage.error('删除菜单失败，请检查网络连接或联系管理员')
      throw error
    })
}

/** 获取菜单列表（支持父级筛选） - GET /api/menu/items */
export const getMenuItems = (onlyParent?: boolean) => {
  const params = onlyParent ? { onlyParent: true } : {}
  return request.get<ApiResp<MenuItem[]>>('/api/menu/items', { params })
}

/* ------------------------------------------------------------------ */
/*  工具函数                                                           */
/* ------------------------------------------------------------------ */

/** 菜单类型映射 */
export const MENU_TYPE_MAP = {
  'MENU': '菜单',
  'BUTTON': '按钮',
  'DIRECTORY': '目录'
} as const

/** 获取菜单类型显示文本 */
export const getMenuTypeText = (type: string): string => {
  return MENU_TYPE_MAP[type as keyof typeof MENU_TYPE_MAP] || type
}

/** 获取菜单类型标签类型 */
export const getMenuTypeTagType = (type: string): string => {
  switch (type) {
    case 'MENU': return 'primary'
    case 'BUTTON': return 'warning'
    case 'DIRECTORY': return 'info'
    default: return 'default'
  }
}

/** 将后端菜单数据转换为树形选择器选项 */
export const transformToTreeOptions = (menus: MenuItem[]): MenuTreeNode[] => {
  return menus.map(menu => ({
    ...menu,
    label: menu.name,
    value: menu.id || 0,
    children: menu.children ? transformToTreeOptions(menu.children) : undefined
  }))
}

/** 获取父级菜单选项（用于下拉选择） */
export const getParentMenuOptions = async (): Promise<MenuTreeNode[]> => {
  try {
    // 使用获取菜单项接口，只获取父级菜单
    const response = await getMenuItems(true)
    const menuData = response.data?.data || response.data || []
    const menus = Array.isArray(menuData) ? menuData : []

    // 过滤出可以作为父级的菜单（通常是目录类型或菜单类型）
    const parentMenus = menus.filter((menu: MenuItem) =>
      menu.menuType === 'DIRECTORY' || menu.menuType === 'MENU'
    )

    return [
      { id: 0, name: '顶级菜单', label: '顶级菜单', value: 0 },
      ...transformToTreeOptions(parentMenus)
    ]
  } catch (error) {
    console.error('获取父级菜单选项失败:', error)
    return [{ id: 0, name: '顶级菜单', label: '顶级菜单', value: 0 }]
  }
}

/** 构建菜单树结构 */
export const buildMenuTree = (menus: MenuItem[]): MenuItem[] => {
  const menuMap = new Map<number, MenuItem>()
  const rootMenus: MenuItem[] = []

  // 首先创建所有菜单的映射
  menus.forEach(menu => {
    if (menu.id) {
      menuMap.set(menu.id, { ...menu, children: [] })
    }
  })

  // 构建父子关系
  menus.forEach(menu => {
    if (!menu.id) return

    const menuItem = menuMap.get(menu.id)!

    if (menu.parentId && menu.parentId !== 0 && menuMap.has(menu.parentId)) {
      // 有父级菜单
      const parent = menuMap.get(menu.parentId)!
      if (!parent.children) parent.children = []
      parent.children.push(menuItem)
    } else {
      // 顶级菜单
      rootMenus.push(menuItem)
    }
  })

  // 按sort字段排序
  const sortMenus = (menus: MenuItem[]) => {
    menus.sort((a, b) => (a.sort || 0) - (b.sort || 0))
    menus.forEach(menu => {
      if (menu.children && menu.children.length > 0) {
        sortMenus(menu.children)
      }
    })
  }

  sortMenus(rootMenus)
  return rootMenus
}

/** 扁平化菜单树（用于搜索） */
export const flattenMenuTree = (menus: MenuItem[]): MenuItem[] => {
  const result: MenuItem[] = []

  const flatten = (items: MenuItem[]) => {
    items.forEach(item => {
      result.push(item)
      if (item.children && item.children.length > 0) {
        flatten(item.children)
      }
    })
  }

  flatten(menus)
  return result
}

/** 数据转换：后端数据转前端表单格式 */
export const transformToFormData = (menu: MenuItem): MenuForm => {
  return {
    id: menu.id,
    menuType: menu.menuType || 'MENU',
    parentId: menu.parentId || 0,
    name: menu.name,
    routePath: menu.routePath || '',
    component: menu.component || '',
    permissions: menu.permissions || '',
    archive: menu.archive || false,
    icon: menu.icon || '',
    redirect: menu.redirect || '',
    isShow: menu.isShow !== false, // 默认显示
    sort: menu.sort || 0
  }
}

/** 验证菜单路径格式 */
export const validateRoutePath = (path: string): boolean => {
  if (!path) return true // 空路径也是有效的（比如按钮类型）
  return path.startsWith('/') && /^[a-zA-Z0-9\/_.-]+$/.test(path)
}

/** 生成默认组件路径 */
export const generateDefaultComponent = (routePath: string): string => {
  if (!routePath || !routePath.startsWith('/')) return ''

  const cleanPath = routePath.replace(/^\//, '').replace(/\/$/, '')
  if (!cleanPath) return ''

  return `@/views/${cleanPath}/index.vue`
}

/* ------------------------------------------------------------------ */
/*  模拟数据（开发测试用）                                               */
/* ------------------------------------------------------------------ */
export const getMockMenuData = (): MenuItem[] => {
  return [
    {
      id: 1,
      menuType: 'DIRECTORY',
      parentId: 0,
      name: '系统管理',
      routePath: '/system',
      component: 'Layout',
      permissions: 'system',
      archive: false,
      icon: 'Setting',
      redirect: '/system/user',
      isShow: true,
      sort: 1,
      children: [
        {
          id: 2,
          menuType: 'MENU',
          parentId: 1,
          name: '用户管理',
          routePath: '/system/user',
          component: '@/views/system/user/index.vue',
          permissions: 'system:user:view',
          archive: false,
          icon: 'User',
          redirect: '',
          isShow: true,
          sort: 1
        },
        {
          id: 3,
          menuType: 'MENU',
          parentId: 1,
          name: '角色管理',
          routePath: '/system/role',
          component: '@/views/system/role/index.vue',
          permissions: 'system:role:view',
          archive: false,
          icon: 'UserFilled',
          redirect: '',
          isShow: true,
          sort: 2
        },
        {
          id: 4,
          menuType: 'MENU',
          parentId: 1,
          name: '菜单管理',
          routePath: '/system/menu',
          component: '@/views/system/menu/index.vue',
          permissions: 'system:menu:view',
          archive: false,
          icon: 'Menu',
          redirect: '',
          isShow: true,
          sort: 3
        }
      ]
    },
    {
      id: 5,
      menuType: 'MENU',
      parentId: 0,
      name: '首页',
      routePath: '/dashboard',
      component: '@/views/Dashboard/index.vue',
      permissions: 'dashboard:view',
      archive: false,
      icon: 'House',
      redirect: '',
      isShow: true,
      sort: 0
    }
  ]
}

/** 批量操作 */
export const batchUpdateMenuStatus = (ids: number[], isShow: boolean) => {
  return request.post<ApiResp>('/api/menu/batch-status', { ids, isShow })
}

export const batchDeleteMenus = (ids: number[]) => {
  return request.post<ApiResp>('/api/menu/batch-delete', { ids })
}
